package adminservice

import (
	"errors"
	"go-middle/app/common/model/admin"
	"go-middle/app/common/model/admin_online"
	"go-middle/app/common/model/role"
	"go-middle/app/common/model/role_has_menu"
	"go-middle/library/token"

	"github.com/gogf/gf/crypto/gmd5"
	"github.com/gogf/gf/database/gdb"
	"github.com/gogf/gf/os/glog"
	"github.com/gogf/gf/os/gtime"
	"github.com/gogf/gf/text/gstr"
	"github.com/gogf/gf/util/gconv"
	"github.com/gogf/gf/util/grand"
)

//获取用户列表分页
func GetAdminList(param admin.SelectPageReq) (total int, out []*admin.RespUserInfo) {
	model := admin.Model
	if param.Search != "" {
		v := "%" + param.Search + "%"
		model = model.Where("user like ? or mobile like ? or name like ?", v, v, v)
	}
	if param.Sex != "" {
		model = model.Where("sex = ?", param.Sex)
	}
	if param.State != "" {
		model = model.Where("state = ?", param.State)
	}
	if param.UserType != "" {
		model = model.Where("user_type = ?", param.UserType)
	}
	if param.RoleId != 0 {
		model = model.Where("find_in_set(?,roles)", param.RoleId)
	}
	model = model.Where("delete_time = 0 and id <> 1")
	total, err := model.Count()
	if err != nil {
		glog.Error(err)
		return
	}
	out, err = model.
		Page(param.Page, param.Limit).
		Order("id desc").
		GetPageList()
	if err != nil {
		glog.Error(err)
		return
	}
	return
}

//重置用户密码
func ResetPwd(id int64, password string) error {
	m := GetAdminById(id)
	if password == "" {
		password = m.Mobile[5:]
	}
	m.Password = gmd5.MustEncryptString(gconv.String(m.CreateTime) + password + m.Salt)
	_, err := m.Update()
	if err != nil {
		glog.Error(err)
		return err
	}
	//强制下线
	res, _ := admin_online.Model.Where("user=?", m.User).FindAll()
	for _, v := range res {
		_ = token.SessionStore.RemoveAll(v.Token)
		_, _ = v.Delete()
	}
	return nil
}

//保存用户信息
func SaveAdmin(info interface{}) error {
	add, ok1 := (info).(admin.ReqAdd)
	edit, ok2 := (info).(admin.ReqEdit)
	if !ok1 && !ok2 {
		return errors.New("参数类型错误")
	}
	if ok2 {
		mode, _ := admin.FindOne("id=?", edit.Id)
		//编辑
		mode.User = edit.User
		mode.Mobile = edit.Mobile
		mode.Name = edit.Name
		mode.Sex = edit.Sex
		mode.State = edit.State
		mode.Remark = edit.Remark
		mode.Roles = edit.Roles
		mode.UpdateTime = gtime.Now().Unix()
		_, err := mode.Update()
		if err != nil {
			return err
		}
	} else {
		var mode admin.Entity
		//新增
		mode.User = add.User
		mode.Mobile = add.Mobile
		mode.Name = add.Name
		mode.Sex = add.Sex
		mode.State = add.State
		mode.Remark = add.Remark
		mode.Roles = add.Roles
		mode.Salt = grand.Letters(6)
		mode.CreateTime = gtime.Now().Unix()
		mode.UpdateTime = gtime.Now().Unix()
		mode.Password = gmd5.MustEncryptString(gconv.String(mode.CreateTime) + mode.Mobile[6:] + mode.Salt)
		_, err := mode.Insert()
		if err != nil {
			return err
		}
	}
	return nil
}

//删除用户
func DelAdmin(ids []int64) error {
	_, err := admin.Model.Where("id in (?) and id <> 1", ids).Data(gdb.Map{
		"delete_time": gtime.Now().Unix(),
	}).Update()
	return err
}

//获取用户信息
func GetAdminById(id int64) *admin.Entity {
	data, _ := admin.Model.FindOne("id=?", id)
	return data
}

//修改密码
func ChangePwd(user admin.Entity, param admin.ReqChangePwd) error {
	if gmd5.MustEncryptString(gconv.String(user.CreateTime)+param.OldPwd+user.Salt) != user.Password {
		return errors.New("旧密码不正确")
	}
	user.Password = gmd5.MustEncryptString(gconv.String(user.CreateTime) + param.NewPwd + user.Salt)
	_, err := user.Update()
	if err != nil {
		return err
	}
	return nil
}

//从指定角色移除用户
func DelRoleHasAdmin(param role.ReqRoleUser) (err error) {
	_, err = admin.Model.Where("id in (?) and roles = ?", param.Ids, param.RoleId).Delete()
	if err != nil {
		return err
	}
	list, _ := admin.Model.Where("id in (?) and find_in_set(?,roles)", param.Ids, param.RoleId).All()
	for _, v := range list {
		arr := gstr.Explode(",", v.Roles)
		var arrNew []string
		for _, vv := range arr {
			if vv != gconv.String(param.RoleId) {
				arrNew = append(arrNew, vv)
			}
		}
		v.Roles = gstr.Implode(",", arrNew)
		_, e := v.Update()
		if e != nil {
			glog.Error("[角色移除用户]" + e.Error())
		}
	}
	return
}

//指定角色加入用户
func AddRoleHasAdmin(param role.ReqRoleUser) (err error) {
	_, err = admin.Model.Where("id in (?) and roles = ''", param.Ids).
		Data(gdb.Map{
			"roles": param.RoleId,
		}).Update()
	if err != nil {
		return err
	}
	list, _ := admin.Model.Where("id in (?) and roles <> ?", param.Ids, param.RoleId).All()
	for _, v := range list {
		arr := gstr.Explode(",", v.Roles)
		roles := gconv.String(param.RoleId)
		if !gstr.InArray(arr, roles) {
			arr = append(arr, roles)
		}
		v.Roles = gstr.Implode(",", arr)
		_, e := v.Update()
		if e != nil {
			glog.Error("[角色添加用户]" + e.Error())
		}
	}
	return
}

//删除角色
func RoleDelete(id int) error {
	_, err := role.Model.Where("id = ?", id).Delete()
	if err != nil {
		glog.Error(err)
		return err
	}
	return nil
}

//保存菜单信息
func SaveRole(info interface{}) error {
	add, ok1 := (info).(role.ReqRoleAdd)
	edit, ok2 := (info).(role.ReqRoleEdit)
	if !ok1 && !ok2 {
		return errors.New("参数类型错误")
	}
	if ok2 {
		//编辑
		mode, _ := role.FindOne("id=?", edit.Id)
		mode.Name = edit.Name
		mode.Sort = edit.Sort
		mode.Remark = edit.Remark
		mode.UpdateTime = gtime.Now().Unix()
		_, err := mode.Update()
		if err != nil {
			return err
		}
	} else {
		var mode role.Entity
		//新增
		mode.Name = add.Name
		mode.Sort = add.Sort
		mode.Remark = add.Remark
		mode.CreateTime = gtime.Now().Unix()
		mode.UpdateTime = gtime.Now().Unix()
		_, err := mode.Insert()
		if err != nil {
			return err
		}
	}
	return nil
}

//保存角色分配权限
func SaveRoleHasMenu(param role_has_menu.ReqRolePermission) error {
	_, err := role_has_menu.Model.Where("role_id=?", param.RoleId).Delete()
	if err != nil {
		return err
	}
	if len(param.Ids) > 0 {
		var mp []gdb.Map
		for _, v := range param.Ids {
			mp = append(mp, gdb.Map{
				"role_id": param.RoleId,
				"menu_id": v,
			})
		}
		_, err = role_has_menu.Model.Data(mp).Insert()
		if err != nil {
			return err
		}
	}
	return nil
}
